package com.xiaoluo.lottery.jobs;


import com.xiaoluo.lottery.common.enums.HBStatusEnums;
import com.xiaoluo.lottery.common.utils.ApplicationContextUtil;
import com.xiaoluo.lottery.common.utils.FrequencyUtil;
import com.xiaoluo.lottery.dao.HbInfoJdbcDao;
import com.xiaoluo.lottery.entity.HbInfo;
import com.xiaoluo.lottery.vo.DataPage;
import com.xl.tool.util.DateUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.List;

/**
 * Project : pms
 * Package : com.xiaoluo.lottery.jobs
 * Created by Willian.
 * Date  : 2016/3/9 11:00.
 */
@Component
public class WeiXinPayTask {

    private static Logger logger = LoggerFactory.getLogger(WeiXinPayTask.class);

    private final static Integer MIN_AMOUNT = 100;
    private final static Integer MAX_AMOUNT = 20000;

    @Autowired
    private HbInfoJdbcDao hbInfoJdbcDao;


    /**
     * 查询微信红包的发放状态
     * 1、获取微信红包发送中的记录；
     * 2、查询微信红包状态
     */
    public void execute(){
        logger.info("WeiXinPayTask execute.");

        Date date =  DateUtils.addMinutes(new Date(),-2);
        List<HbInfo> list = hbInfoJdbcDao.select(HBStatusEnums.FAILED.getValue(),date,MIN_AMOUNT,MAX_AMOUNT);
        /**
         * 自动补发红包
         * process(list);
         *
         */

    }

    /**
     * 自动发送红包
     * @param list
     */
    private void process(List<HbInfo> list){
        if(list != null && list.size() > 0){
            for (HbInfo hb : list){
                logger.info("Resend wxHb:{}",hb.getHbCode());
                if(FrequencyUtil.can(hb.getOpenid())){
                    ApplicationContextUtil.weixinService.reSendHb(hb.getHbCode());
                }
            }
        }
    }

    /**
     * 更新红包状态
     */
    public void update(){
        logger.info("WeiXinPayTask update.");
        Date date =  DateUtils.addMinutes(new Date(),-3);
        List<HbInfo> list = hbInfoJdbcDao.select(HBStatusEnums.SENT.getValue(),date);
        if(list != null && list.size() >0){
            for (HbInfo hb:list){
                logger.info("get wxHbInfo:{}",hb.getHbCode());
                ApplicationContextUtil.weixinService.gethbinfo(hb.getHbCode());
            }
        }

    }

}
